// pages/game/hxGame/index.js
const http = require('../../../utils/http.js')
let filter = require('../../../utils/intercept.js')
var barrage_style_arr = [];

var barrage_style_obj ={};

var phoneWidth = 0;

var timers = [];

var timer ;
//心跳检测
// var heartCheck = {
//   timeout: 60000,
//   timeoutObj: null,
//   serverTimeoutObj: null,
//   reset:function(){
//     clearTimeout(this.timeoutObj);
//     clearTimeout(this.serverTimeoutObj);
//   },
//   start:function(){
//     this.timeoutObj=setTimeout(()=>{
//       console.log('发送ping')
//       wx.sendSocketMessage({
//         data: 'ping',
//       })
//       this.serverTimeoutObj=setTimeout(()=>{
//         wx.closeSocket()
//       },this.timeout)
//     },this.timeout)
//   }
// }
let lockReconnect=false
let tt
var heartCheck = {
  timeout: 60000,
  timeoutObj: null,
  serverTimeoutObj: null,
  start: function(){
  //console.log('start');
  var self = this;
  this.timeoutObj && clearTimeout(this.timeoutObj);
  this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
  this.timeoutObj = setTimeout(function(){
    //这里发送一个心跳，后端收到后，返回一个心跳消息，
    // console.log('55555');
    // ws.send("123456789");
    self.serverTimeoutObj = setTimeout(function() {
    // console.log(111);
    // console.log(ws);
    wx.closeSocket()
    // createWebSocket();
    }, self.timeout);

  }, this.timeout)
  }
}
Page(filter.identityFilter({

  /**
   * 页面的初始数据
   */
  data: {
    animationData:{},
    animationData1:{},
    qdImg:false,
    textnum:false,
    btnlist:true,
    sqhb:false,//授权海报相册
    hbBo:false,//显示海报
    hbszNum:0,
    textarea:'',//留言文字
    hbTxt:'',//海报文字
    zmdTxt:'',
    zmdFalg:false,
    indicatorDots: true,
    myVideobo:false,
    myVideobo1:false,
    quanBo:false,
    hbnum:false,
    sceneNum:16,

   autoplay: true,

   interval: 3000,

   duration: 500,

   barrageTextColor:"#D3D3D3",

   barrage_inputText:"flex",//flex//none

   barrage_shoottextColor:"black",

   bind_shootValue:"",

   barrage_style:[],

   barragefly_display:"block",//block//none
  },
  gbBtn:function() {
    this.setData({
      hbBo:false,
      hbTxt:''
    })
  },
  hbTxtBtn:function() {
    //console.log(this.data.hbTxt)
    this.setData({
      textnum:false,
      btnlist:true,
      hbnum:false
    })
    if(this.data.hbTxt){
      this.setData({
        hbTxt:this.data.hbTxt,
        hbBo:true
      })
      this.hbImg()
    }else{
      wx.showToast({
        title:'请输入分享海报的祝福语',
        icon:'none'
      })
    }
  },
  //分享海报按钮
  hbBtn:function () {
    console.log('分享海报按钮')
    this.hbImg()
    this.setData({
      //hbnum:true,
      textnum:false,
      btnlist:true,
      hbBo:true
    })
  },
  //生成海报
  hbImg:function() {
    let _width = this.data._width,
        _heigth = this.data._heigth; //屏幕宽与高

    let imgHeigth = this.data.swiperHeight, //原图片高度
        scale = (_width - 40) / _width, //缩小比例
        that = this;
    let imgH = imgHeigth * scale; //绘制时图片显示高度  
    let ctx = wx.createCanvasContext('mycanvas'+this.data.hbszNum);
    //清除画布
    ctx.clearRect(0, 0, _width, imgH)
    // 绘制背景
    ctx.setFillStyle("#fff");
    ctx.fillRect(0, 0, _width, imgH );
    //绘制图片
    // ctx.drawImage(this.data.localImageUrl, 10, 10,200, 500);
    ctx.drawImage(this.data.localImageUrl, 5, 5, _width - 99, imgH - 574);

    // 绘制标题
    ctx.setFontSize(18);
    ctx.setFillStyle('#333');

    let txtWidth = _width - 60 + 30 - 100 - 50; //文字的宽度

    //商品名称 最多两行显示 写法有点LOW，但思路是这样的
    //console.log(this.data.coupon.stockName.length)
    //console.log(that.data.hbTxt)
    // let title = this.data.hbTxt; //商品名称
    // let title2; //商品名称
    // if (title.length > 10) {
    //     title2 = title.slice(10, title.length);
    //     title = title.slice(0, 10);
    //     if (title2.length > 10) {
    //       title2 = title2.slice(0, 9) + ' ...';
    //     }
    // }
    
    // ctx.fillText(title, 70, imgH -730, txtWidth);
    // if(title2){
    //   ctx.fillText(title2, 70, imgH -700 , txtWidth);
    // }
    
    // 绘制价格 '￥'
    // ctx.setFontSize(14);
    // ctx.setFillStyle('#d2aa68');
    // ctx.fillText('￥', 10, imgH -340, txtWidth);
    // 绘制价格
    // ctx.setFontSize(24);
    // ctx.fillText('this.data.coupon.amount', 26, imgH -340, txtWidth);
    // 绘制门市价
    // ctx.setFontSize(14);
    // ctx.setFillStyle('#666');
    // ctx.fillText(`原价￥${'this.data.coupon.costPrice'}`, 115, imgH -820, txtWidth);
    // 显示绘制
    ctx.draw();


    //将生成好的图片保存到本地，需要延迟一会，绘制期间耗时
    setTimeout(function() {
        //console.log(that.data.hbszNum)
        wx.canvasToTempFilePath({
            canvasId: 'mycanvas'+that.data.hbszNum,
            success: function(res) {
                var tempFilePath = res.tempFilePath;
                that.setData({
                  loadImagePath: tempFilePath,
                  hbszNum:that.data.hbszNum +1
                });
            },
            fail: function(res) {
                console.log(res);
            }
        });
    }, 1000);
  },
  //分享获取图片主图尺寸
  onImgLoad: function(e) {
    let oImgW = e.detail.width; //图片原始宽度
    let oImgH = e.detail.height; //图片原始高度
    let imgWidth = 750; //图片设置的宽度
    let scale = imgWidth / oImgW; //比例计算
    let imgHeight = oImgH * scale;

    this.setData({
        swiperHeight: imgHeight,
        canvasW: imgWidth-170,
        canvasH: imgHeight-700
    })
  },
  //点击保存到相册
  saveImg: function() {
    var that=this
    //这里可以打印出返回的临时文件路径
    //console.log('123')
    console.log(that.data.loadImagePath)
    wx.saveImageToPhotosAlbum({
        filePath: that.data.loadImagePath,
        success(res) {
            //console.log('res', res);
            wx.showToast({
                title: '已保存到相册',
                icon: 'success',
                duration: 3000
            })
        },
        fail(res) {
            console.log('错误', res);
            console.log(that.data.loadImagePath)
            if(res.errMsg=="saveImageToPhotosAlbum:fail auth deny"){
              wx.showToast({
                title: '请授权相册',
                icon: 'success'
              })
              that.setData({
                sqhb:true
              })
            }
        }
    })
  },
  xcImg:function() {
    wx.openSetting({//进入小程序授权设置页面
      success(settingdata) {
        console.log(settingdata)
        if (settingdata.authSetting['scope.writePhotosAlbum']) {//用户打开了保存图片授权开关
          //console.log('that.data.loadImagePath')
          that.setData({
            sqhb:false
          })
        } else {//用户未打开保存图片到相册的授权开关
            wx.showModal({
              title: '温馨提示',
              content: '授权失败，请稍后重新获取',
              showCancel: false,
            })
        }
      },
      fail(res){
        console.log(res)
      }
    })
  },
  //我的优惠券
  jhqBtn:function() {
    wx.navigateTo({
      url: '/pages/user/mycoupon/index',
    })
  },
  //抽奖中券跳转
  quanBtn:function() {
    this.setData({
      quanBo:false
    })
    if(this.data.gamejp.productType==1){//商家券
      wx.navigateTo({
        url: '/pages/user/mycoupon/index?id=0',
      })
    }
    if(this.data.gamejp.productType==2){//代金券
      wx.navigateTo({
        url: '/pages/user/mycoupon/index?id=1',
      })
    }
  },
  //视频
  videoBtn:function() {
    //console.log('123123123')
    //console.log(this.data.myVideobo)
    if(this.data.myVideobo){
      this.setData({
        myVideobo1:false
      })
    }
  },
  bindtimeupdateFun:function(e) {
    //console.log(e)
    if(!this.data.myVideobo){
      if(e.detail.currentTime>this.data.gameInfo.videoPlayTime){
        //console.log(e.detail.currentTime)
        this.setData({
          myVideobo:true
        })
      }
    }
    
  },
  //抽奖
  goBtn:function() {
    http.get('/mini/game/lottery',{gameId:this.data.gameInfo.game.id}).then(res => {
      if (res.code == 200) {
        this.setData({
          gamejp:res.data.prize,
          gameInfo:res.data
        })
        if(res.data.prize.productType==9){
          this.setData({
            myVideobo1:true,
            myVideobo:false
          })
        }
        if(res.data.prize.productType!=9){
          this.setData({
            quanBo:true
          })
        }
      }
    })
  },
  btnys:function() {
    this.setData({
      textnum:true,
      btnlist:false,
      hbnum:false
    })
  },
  textBtn:function() {
    this.setData({
      textnum:false,
      btnlist:true,
      hbnum:false
    })
    if(this.data.textarea){
      //console.log(this.data.textarea)
      http.get('/mini/game/shareAddNum',{shareMemberId:this.data.gameInfo.member_id,gameId:this.data.gameInfo.game.id,content:this.data.textarea}).then(res => {
        if (res.code == 200) {
          wx.showToast({
            title:'弹幕发送成功',
            icon:'none'
          })
          this.setData({
            textarea:'',
            gameInfo:res.data
          })
        }
      })
    }else{
      //console.log('请输入留言')
      wx.showToast({
        title:'请输入留言',
        icon:'none'
      })
    }
  },
  qdImgBtn:function(){
    this.setData({
      qdImg:false
    })
  },
  dhFun:function() {
    let that=this
    let animation = wx.createAnimation({
      timingFunction: 'linear'
    })
    this.animation = animation
    animation.translate(-828).step({duration:4000})
    setTimeout(function () {
      animation.translate(0).step({duration:0})
      that.setData({
        animationData : animation.export(),
      })
      that.dhFun();
    }, 500)
  },
  // dhFun1:function(text) {
  //   let that=this
  //   let animation1 = wx.createAnimation({
  //     timingFunction: 'ease'
  //   })
  //   if(text){
  //     that.setData({
  //       zmdTxt:text
  //     })
  //   }
  //   this.animation1 = animation1
  //   animation1.translate(-1080).step({duration:8000})
  //   setTimeout(function () {
  //     animation1.translate(1080).step({duration:0})
  //     that.setData({
  //       animationData1 : animation1.export()
  //     })
  //   }, 8000)
  // },
  linkSocket:function(num){
    let that= this
    wx.connectSocket({
      url: "wss://data.cqncct.com/websocket/"+num,//121.41.55.48:8666//192.168.0.112:8666
      success(){
        console.log('链接成功')
        that.initEventHandle();
      }
    })
  },
  initEventHandle:function(){
    let that=this
    wx.onSocketMessage((res) => {
      //收到消息
      console.log(res.data)
      var data=JSON.parse(res.data)
      if(data.code==200){
        console.log('收到消息---200')
        //this.dhFun1(data.data);
        
        // that.setData({
        //   bind_shootValue:data.data
        // })
        // that.shoot()
        //   this.animation1 = animation1
        //循环几次
        // if(that.data.gameInfo.repeatNum){
        //   //console.log(that.data.gameInfo.repeatNum)
        //   for(var i =1;i<=that.data.gameInfo.repeatNum;i++){
        //     setTimeout(function () {
        //       that.setData({
        //         bind_shootValue:data.data
        //       })
        //       that.shoot()
        //     }, 4000*i)
        //   }
        // }
        
        // wx.showToast({
        //   title: data.data,
        //   icon: 'success'
        // })
        console.log(data.data)
      }
      heartCheck.start()
    })
    wx.onSocketOpen((res) => {
      console.log('链接打开')
      heartCheck.start()
    })
    wx.onSocketError((result) => {
      console.log('链接开打失败')
      //this.reconnet()
      this.reconnect()
    })
    wx.onSocketClose((res) => {
      console.log('已关闭')
      //this.reconnet()
      this.reconnect()
    })
  },
  // reconnet:function() {
  //   if(this.lockReconnect)return;
  //   this.lockReconnect=true
  //   clearTimeout(this.timer)
  //   if(this.data.limit<12){
  //     this.timer=setTimeout(()=>{
  //       this.linkSocket();
  //       this.lockReconnect=false
  //     })
  //     this.setData({
  //       limit:this.data.limit+1
  //     })
  //   }
  // },
  reconnect:function() {
    var that=this
    if(lockReconnect) {
    return;
    };
    lockReconnect = true;
    //没连接上会一直重连，设置延迟避免请求过多
    tt && clearTimeout(tt);
    tt = setTimeout(function () {
      that.linkSocket(that.data.sceneNum?that.data.sceneNum:that.data.gameId);
    lockReconnect = false;
    }, 4000);
  },
  /**
   * 生命周期函数--监听页面加载
   */
  //是否打开弹幕...
 barrageSwitch: function(e){
   //console.log(e);
   //先判断没有打开
   if(!e.detail.value){
   //清空弹幕
     barrage_style_arr = [];
     //设置data的值
     this.setData({
       barrageTextColor:"#D3D3D3",
       barrage_inputText:"none",
       barragefly_display:"none",
       barrage_style:barrage_style_arr,
     });
     //清除定时器
     clearInterval(timer);
   }else{
     this.setData({
       barrageTextColor:"#04BE02",
       barrage_inputText:"flex",
       barragefly_display:"block",
     });
     //打开定时器
       timer= setInterval(this.barrageText_move,100)
   }
 },
 //发射按钮
 shoot: function(e){
   //console.log('asd')
   //字体颜色随机
   var textColor = "rgb("+parseInt(Math.random()*256)+","+parseInt(Math.random()*256)+","+parseInt(Math.random()*256)+")";
   // //设置弹幕字体的水平位置样式
   // var textWidth = -(this.data.bind_shootValue.length*0);
   //设置弹幕字体的垂直位置样式
   var barrageText_height = (Math.random().toFixed(2))*110+260;
   //console.log(barrageText_height)
    barrage_style_obj = {
     // textWidth:textWidth,
     barrageText_height:barrageText_height,
     barrage_shootText:this.data.bind_shootValue,
     barrage_shoottextColor : textColor,
     barrage_phoneWidth:phoneWidth
   };
   barrage_style_arr.push(barrage_style_obj);
   this.setData({
     barrage_style:barrage_style_arr,        //发送弹幕
     bind_shootValue:""                    //清空输入框
   })
     //定时器  让弹幕动起来
     //  this.timer= setInterval(this.barrageText_move,800);
 },
//定时器  让弹幕动起来
 barrageText_move: function(){
   var timerNum = barrage_style_arr.length;
   var textMove ;
   for(var i=0;i<timerNum;i++){
      textMove = barrage_style_arr[i].barrage_phoneWidth;
      //console.log("barrage_style_arr["+i+"].barrage_phoneWidth----------:"+barrage_style_arr[i].barrage_phoneWidth);
      textMove = textMove -5;
     barrage_style_arr[i].barrage_phoneWidth = textMove;
     //走完的移除掉
     if(textMove<=-100){
//         clearTimeout(this.timer);
         barrage_style_arr.splice(0,1);
         i--;
         //全部弹幕运行完
         if(barrage_style_arr.length==0){
           this.setData({
             barrage_style:barrage_style_arr,
           })
           // clearInterval(this.timer);
           return;
         }
     }
     //console.log("第"+i+"个定时器:",textMove);
     this.setData({
       barrage_style:barrage_style_arr,
     })
   }
 },
 //绑定发射输入框，将值传递给data里的bind_shootValue，发射的时候调用
//  bind_shoot:function(e){
//    this.setData({
//      bind_shootValue:e.detail.value
//    })
//  },
  onLoad: function (options) {
    var that = this;
    if(options.scene){
      this.setData({
        sceneNum:options.scene
      })
    }
    //console.log(options.myId)
    //分享
    if (options.myId && options.gameId) {
      this.setData({
        shareMemberId:options.myId,
        gameId:options.gameId
      })
      // wx.showToast({
      //   title:'myId='+options.myId,
      //   icon:'none'
      // })
      //console.log('myId'+options.myId)
      //console.log('gameId'+options.gameId)
      //alert('分享值以获取'+this.data.shareMemberId)
    }
    //alert('分享值以获取----外'+this.data.shareMemberId)
    //初始参数
    http.get('/mini/game/init/'+(options.scene?options.scene:this.data.gameId)).then(res => {
      if (res.code == 200) {
        this.setData({
            gameInfo: res.data
        })
        wx.getImageInfo({
            src: that.data.gameInfo.game.borderImg, //服务器返回的带参数的小程序码地址
            success: function(res) {
              //console.log(_type)
                //res.path是网络图片的本地地址
                that.setData({
                    localImageUrl: res.path,
                })
                console.log(that.data.localImageUrl)
            },
            fail: function(res) {
                //失败回调
                console.log(res)
                // console.log(urlArr[_type])
                // console.log('错误-res', _type, res)
            }
        });
      }
    })
    this.linkSocket((options.scene?options.scene:this.data.gameId));
    //this.dhFun();下面动画图片
    timer= setInterval(this.barrageText_move,50)
    var that = this;

   //获取屏幕的宽度
     wx.getSystemInfo({
       success: function(res) {
          that.setData({
               barrage_phoneWidth:res.windowWidth-100,
          })
       }
     })
     phoneWidth = that.data.barrage_phoneWidth;
     //console.log(phoneWidth);
    // let animation = wx.createAnimation({
    //   timingFunction: 'ease'
    // })
    // let animation2 = wx.createAnimation({
    //   timingFunction: 'ease'
    // })
    // this.animation = animation
    // this.animation2 = animation2
    // //var asd=(360*10)-(360/this.data.list1.length)*res.data.index-360/this.data.list1.length
    // //animation.rotate(45).step({duration: 500,timingFunction:'ease-in-out'})
    // animation.translate(-1500).step({duration:2000})
    // animation2.translate(-1500).step({duration:2000})
    // //animation.rotate((360*10)-(360/this.data.list1.length)*res.data.index-90-360/this.data.list1.length/2).step({duration:2000})
    // this.setData({
    //   animationData : animation.export()
    // })
    // setTimeout(function () {
    //   animation.translate(1250).step({duration:0})
    //   that.setData({
    //     animationData : animation.export(),
    //     animationData2 : animation2.export()
    //   })
    //   // animation2.translate(2500).step({duration:2000})
    //   // that.setData({
    //   //   animationData2 : animation2.export()
    //   // })
    // }, 2000)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this;
    wx.getSystemInfo({
      success(res) {
          that.setData({
              _width: res.windowWidth,
              _heigth: res.windowHeight
          })
      }
    })
    //弹幕数据
    // http.get('/game/barrage/random',{gameId:this.data.sceneNum?this.data.sceneNum:this.data.gameId}).then(res => {
    //   if(res.code==200){
    //     //console.log(res)
    //     for(var i =0; i<res.data.result.length;i++){
    //       var mi=i
    //       setTimeout(function () {
    //         console.log(res.data.result[mi].content)
    //         that.setData({
    //           bind_shootValue:res.data.result[mi].content
    //         })
    //         that.shoot()
    //       }, res.data.time*i)
    //     }
    //   }
    // })
    //分享
    if(this.data.shareMemberId){
      //alert('分享')
      http.get('/mini/game/shareAddNum',{shareMemberId:this.data.shareMemberId,gameId:this.data.gameId}).then(res => {
        if(res.code==200){
          //alert('200')d
        }
      })
    }
    http.get('/mini/game/init/'+(this.data.sceneNum?this.data.sceneNum:this.data.gameId)).then(res => {
      if (res.code == 200) {
        this.setData({
            gameInfo: res.data
        })
        wx.getImageInfo({
            src: that.data.gameInfo.game.borderImg, //服务器返回的带参数的小程序码地址
            success: function(res) {
              //console.log(_type)
                //res.path是网络图片的本地地址
                that.setData({
                    localImageUrl: res.path,
                })
                console.log(that.data.localImageUrl)
            },
            fail: function(res) {
                //失败回调
                console.log(res)
                // console.log(urlArr[_type])
                // console.log('错误-res', _type, res)
            }
        });
      }
    })
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    //console.log(this.data.gameInfo.member_id)
    //console.log(this.data.gameInfo.game.id)
    if(res.from==='button'){
      return {
        title: '分享抽奖',
        //imageUrl: '/images/share.jpg',id
        path: '/pages/game/hxGame/index?myId=' + this.data.gameInfo.member_id+ "&gameId=" + this.data.gameInfo.game.id
      }
    }
  }
}))